#!/bin/bash

# 一键构建本地数据库脚本 (Linux/macOS版本)
# 支持MySQL和PostgreSQL

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印标题
echo -e "${BLUE}========================================"
echo -e "    中山大学研究生院校企对接平台"
echo -e "        数据库一键构建脚本"
echo -e "========================================${NC}"
echo

# 检查Docker是否安装
echo -e "${BLUE}检查Docker环境...${NC}"
if ! command -v docker &> /dev/null; then
    echo -e "${RED}错误: Docker未安装，请先安装Docker${NC}"
    echo "安装指南: https://docs.docker.com/get-docker/"
    exit 1
fi

echo -e "${GREEN}Docker环境检查通过${NC}"

# 检查Docker Compose是否可用
if ! command -v docker-compose &> /dev/null; then
    echo -e "${RED}错误: Docker Compose不可用${NC}"
    exit 1
fi

echo -e "${GREEN}Docker Compose检查通过${NC}"
echo

# 选择数据库类型
echo -e "${YELLOW}请选择要构建的数据库类型:${NC}"
echo "1. MySQL (推荐)"
echo "2. PostgreSQL"
echo "3. 仅启动数据库服务 (MySQL + Redis)"
echo "4. 启动完整环境 (MySQL + Redis + 应用)"
echo "5. 清理所有数据并重新构建"
echo
read -p "请输入选择 (1-5): " choice

case $choice in
    1)
        echo
        echo -e "${BLUE}开始构建MySQL数据库环境...${NC}"
        ;;
    2)
        echo
        echo -e "${BLUE}开始构建PostgreSQL数据库环境...${NC}"
        echo -e "${YELLOW}注意: 需要修改docker-compose.yml中的数据库配置${NC}"
        ;;
    3)
        echo
        echo -e "${BLUE}启动数据库服务 (MySQL + Redis)...${NC}"
        docker-compose up -d mysql redis
        if [ $? -ne 0 ]; then
            echo -e "${RED}数据库服务启动失败${NC}"
            exit 1
        fi
        wait_for_services
        show_info
        exit 0
        ;;
    4)
        echo
        echo -e "${BLUE}启动完整环境 (MySQL + Redis + 应用)...${NC}"
        docker-compose up -d
        if [ $? -ne 0 ]; then
            echo -e "${RED}完整环境启动失败${NC}"
            exit 1
        fi
        wait_for_services
        show_info
        exit 0
        ;;
    5)
        echo
        echo -e "${YELLOW}警告: 这将删除所有数据并重新构建${NC}"
        read -p "确认继续? (y/N): " confirm
        if [[ ! $confirm =~ ^[Yy]$ ]]; then
            echo "操作已取消"
            exit 0
        fi
        
        echo -e "${BLUE}停止并删除所有容器和卷...${NC}"
        docker-compose down -v
        docker system prune -f
        
        echo -e "${BLUE}重新构建环境...${NC}"
        docker-compose up -d --build
        if [ $? -ne 0 ]; then
            echo -e "${RED}重新构建失败${NC}"
            exit 1
        fi
        wait_for_services
        show_info
        exit 0
        ;;
    *)
        echo -e "${RED}无效选择${NC}"
        exit 1
        ;;
esac

# 启动数据库服务
echo -e "${BLUE}启动数据库服务...${NC}"
docker-compose up -d mysql redis
if [ $? -ne 0 ]; then
    echo -e "${RED}数据库服务启动失败${NC}"
    exit 1
fi

# 等待服务启动
wait_for_services() {
    echo
    echo -e "${BLUE}等待服务启动完成...${NC}"
    sleep 10
    
    # 检查MySQL服务状态
    echo -e "${BLUE}检查MySQL服务状态...${NC}"
    for i in {1..30}; do
        if docker exec sysu-giep-mysql mysqladmin ping -h localhost --silent 2>/dev/null; then
            echo -e "${GREEN}MySQL服务运行正常${NC}"
            break
        fi
        if [ $i -eq 30 ]; then
            echo -e "${RED}MySQL服务启动失败${NC}"
            exit 1
        fi
        echo -e "${YELLOW}MySQL服务可能还在启动中，请稍等... ($i/30)${NC}"
        sleep 2
    done
    
    # 检查Redis服务状态
    echo -e "${BLUE}检查Redis服务状态...${NC}"
    for i in {1..10}; do
        if docker exec sysu-giep-redis redis-cli ping >/dev/null 2>&1; then
            echo -e "${GREEN}Redis服务运行正常${NC}"
            break
        fi
        if [ $i -eq 10 ]; then
            echo -e "${RED}Redis服务启动失败${NC}"
            exit 1
        fi
        echo -e "${YELLOW}Redis服务可能还在启动中，请稍等... ($i/10)${NC}"
        sleep 1
    done
}

# 初始化数据库
init_database() {
    echo
    echo -e "${BLUE}初始化数据库结构...${NC}"
    
    # 检查是否有Go环境
    if ! command -v go &> /dev/null; then
        echo -e "${YELLOW}Go环境未找到，跳过数据库迁移${NC}"
        echo -e "${YELLOW}请手动运行: go run cmd/server/main.go${NC}"
        return
    fi
    
    # 设置环境变量
    export DATABASE_URL="mysql://root:password@localhost:3306/sysu_giep?charset=utf8mb4&parseTime=True&loc=Local"
    
    echo -e "${BLUE}运行数据库迁移...${NC}"
    
    # 启动应用进行数据库迁移
    go run cmd/server/main.go &
    APP_PID=$!
    
    # 等待应用启动
    sleep 5
    
    # 检查应用是否启动成功
    for i in {1..10}; do
        if curl -s http://localhost:8080/api/v1/health >/dev/null 2>&1; then
            echo -e "${GREEN}应用启动成功，数据库迁移完成${NC}"
            break
        fi
        if [ $i -eq 10 ]; then
            echo -e "${YELLOW}应用可能还在启动中...${NC}"
        fi
        sleep 2
    done
    
    # 停止应用进程
    kill $APP_PID 2>/dev/null
}

# 显示信息
show_info() {
    echo
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}        数据库构建完成！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo
    echo -e "${BLUE}服务信息:${NC}"
    echo "MySQL:     localhost:3306"
    echo "Redis:     localhost:6379"
    echo "数据库名:   sysu_giep"
    echo "用户名:     root"
    echo "密码:       password"
    echo
    echo -e "${BLUE}管理命令:${NC}"
    echo "查看日志:   docker-compose logs -f mysql"
    echo "进入MySQL: docker exec -it sysu-giep-mysql mysql -u root -p"
    echo "进入Redis: docker exec -it sysu-giep-redis redis-cli"
    echo "停止服务:   docker-compose down"
    echo "重启服务:   docker-compose restart"
    echo
    echo -e "${BLUE}下一步:${NC}"
    echo "1. 运行应用: go run cmd/server/main.go"
    echo "2. 访问API: http://localhost:8080/api/v1/health"
    echo "3. 查看文档: http://localhost:8080/swagger/index.html"
    echo
    
    # 询问是否启动应用
    read -p "是否现在启动应用? (y/N): " start_app
    if [[ $start_app =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}启动应用服务...${NC}"
        go run cmd/server/main.go
    fi
}

# 执行主要流程
wait_for_services
init_database
show_info
